from _socket import AF_INET, SOCK_STREAM, SOL_SOCKET, SO_REUSEADDR
from socket import socket

from PyQt5.QtCore import QThread, QSettings
from pyaudio import PyAudio
import wave
import os
import logging.config
import traceback
from util.Tools import Tools

settings = QSettings(Tools.resource_path("config\\config.ini"), QSettings.IniFormat)
settings.setIniCodec("UTF-8")
logging.config.fileConfig(os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "config\\logging.ini"))
logging.getLogger("infoLogger")

# TODO 语音播报
class Speech(QThread):
    def __init__(self,filename):
        try:
            super().__init__()
            self.p = PyAudio()
            self.CHUNK = 1024
            self.FileName=filename
        except Exception as f:
            print(f)

    def run(self):
        try:
            self.playSpeech()
        except Exception as f:
            print(f)

    def playSpeech(self):
        '''播报语音'''
        try:
            wf = wave.open(self.FileName, 'rb')
            stream = self.p.open(format=self.p.get_format_from_width(wf.getsampwidth()),
                                 channels=wf.getnchannels(), rate=wf.getframerate(),
                                 output=True)  # 打开数据流--【获取音频格式信息】
            # output=True   输出的意思
            data = wf.readframes(self.CHUNK)  # 读取数据
            while data != b'' and not (stream.is_stopped()):
                # stream.is_stopped()  流是否停止，如果停止返回True
                stream.write(data)  # 播放
                data = wf.readframes(self.CHUNK)
            stream.stop_stream()
            stream.close()
        except Exception:
            logging.error(traceback.format_exc())


class DemoSpeech(QThread):
    def __init__(self,filename):
        try:
            super().__init__()
            self.p = PyAudio()
            self.CHUNK = 1024
            self.FileName=filename
            self.POST = settings.value("SocketService/HTTP_IP_PORT")
            self.add = ('', int(self.POST))
            # 创建一个tcp套接字
            self.listen_socket = socket(AF_INET, SOCK_STREAM)
            # 允许立即使用上次绑定的port
            self.listen_socket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
            # 绑定
            self.listen_socket.bind(self.add)
            # 变为被动，并制定队列的长度
            self.listen_socket.listen(128)
        except Exception as f:
            print(f)

    def run(self):
        try:
            while True:
                # 等待新客户端到来
                client_socket, client_address = self.listen_socket.accept()
                # new_process = threading.Thread(target=self.handleRequest, args=(client_socket,))
                # new_process.start()
                # 因为线程是共享同一个套接字，所以主线程不能关闭，否则子线程就不能再使用这个套接字了
                # self.playSpeech(client_socket)
        except Exception as f:
            print(f)

    def playSpeech(self):
        '''播报语音'''
        try:
            wf = wave.open(self.FileName, 'rb')
            stream = self.p.open(format=self.p.get_format_from_width(wf.getsampwidth()),
                                 channels=wf.getnchannels(), rate=wf.getframerate(),
                                 output=True)  # 打开数据流--【获取音频格式信息】
            # output=True   输出的意思
            data = wf.readframes(self.CHUNK)  # 读取数据
            while data != b'' and not (stream.is_stopped()):
                # stream.is_stopped()  流是否停止，如果停止返回True
                stream.write(data)  # 播放
                data = wf.readframes(self.CHUNK)
            stream.stop_stream()
            stream.close()
        except Exception:
            logging.error(traceback.format_exc())



